﻿// lightShaders declarations
void DirectionalLight(	in int i,
						in vec3 normal,
						inout vec4 ambient,
						inout vec4 diffuse,
						inout vec4 specular);
void PointLight(	in int i,
					in vec3 eye,
					in vec3 ecPosition3,
					in vec3 normal,
					inout vec4 ambient,
					inout vec4 diffuse,
					inout vec4 specular);
void SpotLight(	in int i,
				in vec3 eye,
				in vec3 ecPosition3,
				in vec3 normal,
				inout vec4 ambient,
				inout vec4 diffuse,
				inout vec4 specular);

//  textureShader declarations
void applyTexture2D(in sampler2D texUnit, in int type, inout vec4 color);

// interpolated from vertex shader
varying vec3 position, ecPosition3, normal;
varying vec4 ecPosition4;

// texture
uniform sampler2D myTexture;

// cut parameters
uniform vec3 back, front, reference;
uniform float minAxis, maxAxis, minAngle, maxAngle;
uniform vec4 debugColor;

void main()
{
	vec3 axis = front - back;
	vec3 point = position - back;
	
	float len = length(axis);
	float projection = dot(point, axis) / (len * len);
	
	bool discardAxis = false;
	bool discardAngle = false;
	if(projection >= minAxis && projection <= maxAxis)
		discardAxis = true;

	// ---------------------------------
	// angle cut
	if(minAngle < 0.001 && maxAngle > 6.282)
	{
		discardAngle = true;
	}
	else
	{
		vec3 a = normalize(point - (axis * projection));
		vec3 b = normalize(reference);
		vec3 n = normalize(axis);
		float angle = atan(dot(n, cross(a, b)), dot(a, b));
	
		if (angle < 0.0)
			angle = (2.0 * 3.1415926) + angle;
	
		if ( angle >= minAngle && angle <= maxAngle)
			discardAngle = true;
	}	
	// ---------------------------------

	if(discardAxis && discardAngle)
		discard;


	/* end of cutting */

	// Clear the light intensity accumulators
	vec4 color = vec4(0.0);
	vec4 amb = vec4(0.0);
	vec4 diff = vec4(0.0);
	vec4 spec = vec4(0.0);
	vec3 eye;
	
	eye = vec3(0.0, 0.0, 1.0);
	
	// Loop through enabled lights, compute contribution from each
	for (int i = 0; i < 1; i++)
	{
		if (gl_LightSource[i].position.w == 0.0)
			DirectionalLight(i, normal, amb, diff, spec);
		else if (gl_LightSource[i].spotCutoff == 180.0)
			PointLight(i, eye, ecPosition3, normal, amb, diff, spec);
		else
			SpotLight(i, eye, ecPosition3, normal, amb, diff, spec);
	}
	
	color += gl_FrontLightModelProduct.sceneColor;
	color += amb * gl_FrontMaterial.ambient;
	color += diff * gl_FrontMaterial.diffuse;
	color += spec * gl_FrontMaterial.specular;
	
	vec3 texColor = vec3(texture2D(myTexture, gl_TexCoord[0].st));
	if(length(texColor) > 0.0001)
		applyTexture2D(myTexture, 1, color);
	
	gl_FragColor = color;
	//gl_FragColor = debugColor;
}